<?php
if (!defined('SMF'))
	die('Hacking attempt...');

global $smcFunc, $txt, $user_info;
global $dbtables;

// Verify user login, if CheckLogin() returns false return to the calling script/function
if (CheckLogin() == false)
	return;

bigtitle($txt['bnt_team_title']);

//-------------------------------------------------------------------------------------------------

// Pull query string variables.
if (isset($_GET['whichteam']))
	$whichteam = stripnum($_GET['whichteam']);
elseif (isset($_POST['whichteam']))
	$whichteam = stripnum($_POST['whichteam']);
else
	$whichteam = '';

if (isset($_GET['teamwhat']))
	$teamwhat = $_GET['teamwhat'];
elseif (isset($_POST['teamwhat']))
	$teamwhat = $_POST['teamwhat'];
else
	$teamwhat = '';

if (isset($_POST['newcreator']))
	$newcreator = $_POST['newcreator'];
else
	$newcreator = '';

// Get user info.
$result = $smcFunc['db_query']('', '
	SELECT {raw:db_ships}.*, {raw:db_teams}.team_name, {raw:db_teams}.description, {raw:db_teams}.creator, {raw:db_teams}.id
	FROM {raw:db_ships}
	LEFT JOIN {raw:db_teams} ON {raw:db_ships}.team = {raw:db_teams}.id
	WHERE {raw:db_ships}.user_id = {int:user_id}',
	array(
		'db_ships' => $dbtables['ships'],
		'db_teams' => $dbtables['teams'],
		'user_id' => $user_info['id']
	)
);
$playerinfo = $smcFunc['db_fetch_assoc']($result);
$smcFunc['db_free_result']($result);

if ($playerinfo['team_invite'] != "") {
	// Get invite info.
	$result = $smcFunc['db_query']('', '
		SELECT {raw:db_ships}.ship_id, {raw:db_ships}.team_invite, {raw:db_teams}.team_name, {raw:db_teams}.id
		FROM {raw:db_ships}
		LEFT JOIN {raw:db_teams} ON {raw:db_ships}.team_invite = {raw:db_teams}.id
		WHERE {raw:db_ships}.user_id = {int:user_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'db_teams' => $dbtables['teams'],
			'user_id' => $user_info['id']
		)
	);
	$invite_info = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
}

// Get team information.
if (!empty($whichteam))
{
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_teams}
		WHERE id = {int:whichteam}',
		array(
			'db_teams' => $dbtables['teams'],
			'whichteam' => $whichteam
		)
	);
	$team = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
}
else
{
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_teams}
		WHERE id = {int:team}',
		array(
			'db_teams' => $dbtables['teams'],
			'team' => $playerinfo['team']
		)
	);
	$team = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
}

// Determine action to take.
// Already in a switch statement inside SMF . . .

// Information on sigle alliance.
if ($teamwhat == 1)
{	
	showinfo($whichteam,0,$playerinfo,$invite_info,$team);
	LinkBack();
}
// Player wants to leave an alliance
elseif ($teamwhat == 2)
{
	// Read query string variables
	if (isset($_GET['confirmleave']))
		$confirmleave = $_GET['confirmleave'];
	else
		$confirmleave = '';
		
	if (empty($confirmleave))
		echo $txt['bnt_team_confirmleave'], ' <b>', $team['team_name'], '</b>? <a href="', $scripturl, '?action=blacknova;sa=teams;teamwhat=', $teamwhat, ';confirmleave=1;whichteam=', $whichteam, '">', $txt['bnt_yes'], '</a> - <a href="', $scripturl, '?action=blacknova;sa=teams">', $txt['bnt_no'], '</a><br><br>';
    elseif ($confirmleave == 1)
	{
		// Last player in the alliance, delete the alliance.
		if ($team['number_of_members'] == 1)
		{
			// Delete the alliance out of the database.
			$delete = $smcFunc['db_query']('', '
				DELETE FROM {raw:db_teams}
				WHERE id = {int:whichteam}',
				array(
					'db_teams' => $dbtables['teams'],
					'whichteam' => $whichteam
				)
			);
			
			// Remove the alliance marker from the laster person in the alliance.
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET team = 0
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $playerinfo['ship_id']
				)
			);
			
			// Delete all pending invites from the deleted alliance.
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET team_invite = 0
				WHERE team_invite = {int:whichteam}',
				array(
					'db_ships' => $dbtables['ships'],
					'whichteam' => $whichteam
				)
			);
			
			// Remove deleted alliance information from all planets.
			$result = $smcFunc['db_query']('', '
				SELECT DISTINCT sector_id
				FROM {raw:db_planets}
				WHERE owner = {int:ship_id}
				AND base = "Y"',
				array(
					'db_planets' => $dbtables['planets'],
					'ship_id' => $playerinfo['ship_id']
				)
			);
			
			$i = 0;
			while($row = $smcFunc['db_fetch_assoc']($result))
			{
				$sectors[$i] = $row['sector_id'];
				$i++;
			}
			$smcFunc['db_free_result']($result);
			
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_planets}
				SET corp = 0
				WHERE owner = {int:ship_id}',
				array(
					'db_planets' => $dbtables['planets'],
					'ship_id' => $playerinfo['ship_id']
				)
			);
			
			if (!empty($sectors))
			{
				foreach($sectors as $sector)
				{
					calc_ownership($sector);
				}
			}
			defence_vs_defence($playerinfo['ship_id']);
			kick_off_planet($playerinfo['ship_id'],$whichteam);

			$txt['bnt_team_onlymember'] = str_replace("[team_name]", "<b>$team[team_name]</b>", $txt['bnt_team_onlymember']);
			echo $txt['bnt_team_onlymember'], '<br><br>';
			playerlog($playerinfo['ship_id'], LOG_TEAM_LEAVE, "$team[team_name]");
        }
		// Player leaving alliance, not the last player in the alliance
		else
		{
			if ($team['creator'] == $playerinfo['ship_id'])
			{
				echo '
		', $txt['bnt_team_youarecoord'], ' <b>', $team['team_name'], '</b>. ', $txt['bnt_team_relinq'], '<br><br>
		<form action="', $scripturl, '?action=blacknova;sa=teams" method="post">
			<table>
				<tr>
					<td>
						<input type="hidden" name="teamwhat" value=', $teamwhat, ' />
						<input type="hidden" name="confirmleave" value="2" />
						<input type="hidden" name="whichteam" value=', $whichteam, ' />
					</td>
				</tr>
				<tr>
					<td>', $txt['bnt_team_newc'], '</td>
					<td>
						<select name="newcreator">';
				
				$result = $smcFunc['db_query']('', '
					SELECT character_name,ship_id
					FROM {raw:db_ships}
					WHERE team = {int:whichteam}',
					array(
						'db_ships' => $dbtables['ships'],
						'whichteam' => $whichteam
					)
				);
					
				while ($row = $smcFunc['db_num_rows']($result))
				{
					if ($row['ship_id'] != $team['creator'])
						echo '
							<option value=', $row['ship_id'], '>', $row['character_name'];
				}
				$smcFunc['db_free_result']($result);
				
				echo '
						</select>
					</td>
				</tr>
				<tr>
					<td><input type="submit" value=', $txt['bnt_submit'], '></td>
				</tr>
			</table>
		</form>';
		
			}
			else
			{
				$update = $smcFunc['db_query']('', '
					UPDATE {raw:db_ships}
					SET team = 0
					WHERE ship_id = {int:ship_id}',
					array(
						'db_ships' => $dbtables['ships'],
						'ship_id' => $playerinfo['ship_id']
					)
				);
				
				$update = $smcFunc['db_query']('', '
					UPDATE {raw:db_teams}
					SET number_of_members = number_of_members - 1
					WHERE id = {int:whichteam}',
					array(
						'db_teams' => $dbtables['teams'],
						'whichteam' => $whichteam
					)
				);
				
				$result = $smcFunc['db_query']('', '
					SELECT DISTINCT sector_id
					FROM {raw:db_planets}
					WHERE owner = {int:ship_id}
					AND base = "Y"
					AND corp != 0',
					array(
						'db_planets' => $dbtables['planets'],
						'ship_id' => $playerinfo['ship_id']
					)
				);
				
				$i = 0;
				while ($row = $smcFunc['db_num_rows']($result))
				{
					$sectors[$i] = $row['sector_id'];
					$i++;
				}
				$smcFunc['db_free_result']($result);
				
				$update = $smcFunc['db_query']('', '
					UPDATE {raw:db_planets}
					SET corp = 0
					WHERE owner = {int:ship_id}',
					array(
						'db_planets' => $dbtables['planets'],
						'ship_id' => $playerinfo['ship_id']
					)
				);

				if (!empty($sectors))
				{
					foreach($sectors as $sector)
					{
						calc_ownership($sector);
					}
				}

				echo $txt['bnt_team_youveleft'], ' <b>', $team['team_name'], '</b>.<br><br>';
				defence_vs_defence($playerinfo['ship_id']);
				kick_off_planet($playerinfo['ship_id'],$whichteam);
				playerlog($playerinfo['ship_id'], LOG_TEAM_LEAVE, "$team[team_name]");
				playerlog($team['creator'], LOG_TEAM_NOT_LEAVE, "$playerinfo[character_name]");
			}
		}
    }
	// Owner of an alliance is leaving, he is not the last player in the alliance, set a new owner.
	elseif ($confirmleave == 2)
	{ 
		$result = $smcFunc['db_query']('', '
			SELECT character_name
			FROM {raw:db_ships}
			WHERE ship_id = {int:newcreator}',
			array(
				'db_ships' => $dbtables['ships'],
				'newcreator' => $newcreator
			)
		);
		$newcreatorname = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		
		echo $txt['bnt_team_youveleft'], ' <b>', $team['team_name'], '</b> ', $txt['bnt_team_relto'], ' ', $newcreatorname['character_name'], '<br><br>';
		
		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_ships}
			SET team = 0
			WHERE ship_id = {int:ship_id}',
			array(
				'db_ships' => $dbtables['ships'],
				'ship_id' => $playerinfo['ship_id']
			)
		);
		
		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_ships}
			SET team = {int:newcreator}
			WHERE team = {int:creator}',
			array(
				'db_ships' => $dbtables['ships'],
				'newcreator' => $newcreator,
				'creator' => $creator
			)
		);
		
		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_teams}
			SET number_of_members = number_of_members - 1,
				creator = {int:newcreator}
			WHERE id = {int:whichteam}',
			array(
				'db_teams' => $dbtables['teams'],
				'newcreator' => $newcreator,
				'whichteam' => $whichteam
			)
		);
		
		$result = $smcFunc['db_query']('', '
			SELECT DISTINCT sector_id
			FROM {raw:db_planets}
			WHERE owner = {int:ship_id}
			AND base = "Y"
			AND corp != 0',
			array(
				'db_planets' => $dbtables['planets'],
				'ship_id' => $playerinfo['ship_id']
			)
		);
		
		$i = 0;
		while ($row = $smcFunc['db_num_rows']($result))
		{
			$sectors[$i] = $row['sector_id'];
			$i++;
		}
		$smcFunc['db_free_result']($result);
		
		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_planets}
			SET corp = 0
			WHERE owner = {int:ship_id}',
			array(
				'db_planets' => $dbtables['planets'],
				'ship_id' => $playerinfo['ship_id']
			)
		);

		if (!empty($sectors))
		{
			foreach($sectors as $sector)
			{
				calc_ownership($sector);
			}
		}

		playerlog($playerinfo['ship_id'], LOG_TEAM_NEWLEAD, "$team[team_name]|$newcreatorname[character_name]");
		playerlog($newcreator, LOG_TEAM_LEAD,"$team[team_name]");
    }
    LinkBack();
}
// Player joins an alliance.
elseif ($teamwhat == 3)
{
	if ($playerinfo['team'] <> 0)
		echo $txt['bnt_team_leavefirst'], '<br>';
	else
	{
		if ($playerinfo['team_invite'] == $whichteam)
		{
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET team = {int:whichteam},
					team_invite = 0
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $playerinfo['ship_id'],
					'whichteam' => $whichteam
				)
			);
			
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_teams}
				SET number_of_members = number_of_members + 1
				WHERE id = {int:whichteam}',
				array(
					'db_teams' => $dbtables['teams'],
					'whichteam' => $whichteam
				)
			);
			
			echo $txt['bnt_team_welcome'], ' <b>', $team['team_name'], '</b>.<br><br>';
			playerlog($playerinfo['ship_id'], LOG_TEAM_JOIN, "$team[team_name]");
			playerlog($team['creator'], LOG_TEAM_NEWMEMBER, "$team[team_name]|$playerinfo[character_name]");
		}
		else
			echo $txt['bnt_team_noinviteto'], '<br>';
	}
	LinkBack();
}
//
// DOUBLECHECK - unknown functionality
//
elseif ($teamwhat == 4)
{
	echo 'Not implemented yet.';
	LinkBack();
}
// Alliance leader ejects a member.
elseif ($teamwhat == 5)
{
	// Read query string variables
	if (isset($_GET['who']))
		$who = $_GET['who'];
	else
		$who = '';
		
	if (isset($_GET['confirmed']))
		$confirmed = $_GET['confirmed'];
	else
		$confirmed = '';
		
	if ($playerinfo['team'] == $team['id'])
	{
		$result = $smcFunc['db_query']('', '
			SELECT *
			FROM {raw:db_ships}
			WHERE ship_id = {int:who}',
			array(
				'db_ships' => $dbtables['ships'],
				'who' => $who
			)
		);
		
		$whotoexpel = $smcFunc['db_num_rows']($result);
		$smcFunc['db_free_result']($result);
		
		if (!$confirmed)
			echo $txt['bnt_team_ejectsure'], ' ', $whotoexpel['character_name'], '? <a href="', $scripturl, '?action=blacknova;sa=teams;teamwhat=', $teamwhat, ';confirmed=1;who=', $who, '">', $txt['bnt_yes'], '</a> - <a href="', $scripturl, '?action=blacknova;sa=teams">', $txt['bnt_no'], '</a><br>';
		else
		{
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_planets}
				SET corp = 0
				WHERE owner = {int:who}',
				array(
					'db_planets' => $dbtables['planets'],
					'who' => $who
				)
			);
			
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET team = 0
				WHERE ship_id = {int:who}',
				array(
					'db_ships' => $dbtables['ships'],
					'newcreator' => $newcreator,
					'who' => $who
				)
			);

			playerlog($who, LOG_TEAM_KICK, "$team[team_name]");
			echo $whotoexpel['character_name'], ' ', $txt['bnt_team_ejected'], '<br>';
		}
		
	}
	LinkBack();
}
// Player is creating a new alliance.
elseif ($teamwhat == 6)
{
	// Read query string variables.
	if (isset($_POST['teamname']))
		$teamname = $_POST['teamname'];
	else
		$teamname = '';
		
	if (isset($_POST['teamdesc']))
		$teamdesc = $_POST['teamdesc'];
	else
		$teamdesc = '';
		
	if (empty($teamname))
	{
		echo '
		<form action="', $scripturl, '?action=blacknova;sa=teams" method=post>
			', $txt['bnt_team_entername'], ':
			<input type="hidden" name="teamwhat" value=', $teamwhat, '>
			<input type="text" name="teamname" size="40" maxlength="40"><br>
			', $txt['bnt_team_enterdesc'], ':
			<input type="text" name="teamdesc" size="40" maxlength="254"><br>
			<input type="submit" value="', $txt['bnt_submit'], '"><input type="reset" value="', $txt['bnt_reset'], '">
		</form>
		<br><br>';
	}
	else
	{
		$teamname = htmlspecialchars($teamname);
		$teamdesc = htmlspecialchars($teamdesc);
		
		// Create the new alliance in the database.
		$smcFunc['db_insert']('insert',
			$dbtables['teams'],
			array(
				'id' => 'int',
				'creator' => 'int',
				'team_name' => 'string',
				'number_of_members' => 'int',
				'description' => 'string'
			),
			array(
				$playerinfo['ship_id'],
				$playerinfo['ship_id'],
				$teamname,
				1,
				$teamdesc
			),
			''
		);
		
		// Create the new alliance zone.
		$smcFunc['db_insert']('insert',
			$dbtables['zones'],
			array(
				'zone_name' => 'string',
				'owner' => 'int',
				'corp_zone' => 'string',
				'allow_beacon' => 'string',
				'allow_attack' => 'string',
				'allow_planetattack' => 'string',
				'allow_warpedit' => 'string',
				'allow_planet' => 'string',
				'allow_trade' => 'string',
				'allow_defenses' => 'string',
				'max_hull' => 'int',
			),
			array(
				$teamname . '\'s Empire',
				$playerinfo['ship_id'],
				'Y',
				'Y',
				'Y',
				'Y',
				'Y',
				'Y',
				'Y',
				'Y',
				0
			),
			''
		);
		
		// Update alliance information for alliance creator.
		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_ships}
			SET team = {int:ship_id}
			WHERE ship_id = {int:ship_id}',
			array(
				'db_ships' => $dbtables['ships'],
				'ship_id' => $playerinfo['ship_id']
			)
		);
		
		echo $txt['bnt_team_alliance'], ' <b>', $teamname, '</b> ', $txt['bnt_team_hcreated'], '.<br><br>';
		playerlog($playerinfo['ship_id'], LOG_TEAM_CREATE, "$teamname");
	}
	LinkBack();
}
// Invite a player to an alliance.
elseif ($teamwhat == 7)
{
	// Read query string variables.
	if (isset($_POST['invited']))
		$invited = $_POST['invited'];
	else
		$invited = '';
	
	if (isset($_POST['who']))
		$who = $_POST['who'];
	else
		$who = '';
		
	if (empty($invited))
	{
		echo '
		<form action="', $scripturl, '?action=blacknova;sa=teams" method="post">
		<table>
			<tr>
				<td>
					<input type="hidden" name="teamwhat" value="', $teamwhat, '">
					<input type="hidden" name="invited" value="1">
					<input type="hidden" name="whichteam" value="', $whichteam, '">
				</td>
			</tr>
			<tr>
				<td>', $txt['bnt_team_selectp'], ':</td>
				<td>
					<select name="who">';
		
		$result = $smcFunc['db_query']('', '
			SELECT character_name,ship_id
			FROM {raw:db_ships}
			WHERE team <> {int:whichteam}
			ORDER BY character_name ASC',
			array(
				'db_ships' => $dbtables['ships'],
				'whichteam' => $whichteam
			)
		);
		
		while ($row = $smcFunc['db_fetch_assoc']($result))
		{
			if ($row['ship_id'] != $team['creator'])
			echo '
						<option value="', $row['ship_id'], '">', $row['character_name'], '</option>';
		}
		$smcFunc['db_free_result']($result);
		
		echo '
					</select>
				</td>
			</tr>
			<tr>
				<td><input type="submit" value="', $txt['bnt_submit'], '"></td>
			</tr>
		</table>
		</form>';
		
	}
	else
	{
		if ($playerinfo['team'] == $whichteam)
		{
			$result = $smcFunc['db_query']('', '
				SELECT character_name,team_invite
				FROM {raw:db_ships}
				WHERE ship_id = {int:who}',
				array(
					'db_ships' => $dbtables['ships'],
					'who' => $who
				)
			);
			
			$newpl = $smcFunc['db_fetch_assoc']($result);
			$smcFunc['db_free_result']($result);
			
			if ($newpl['team_invite'])
			{
				$txt['bnt_team_isorry'] = str_replace("[name]", $newpl['character_name'], $txt['bnt_team_isorry']);
				echo $txt['bnt_team_isorry'], '<br><br>';
			}
			else
			{
				$update = $smcFunc['db_query']('', '
					UPDATE {raw:db_ships}
					SET team_invite = {int:whichteam}
					WHERE ship_id = {int:who}',
					array(
						'db_ships' => $dbtables['ships'],
						'whichteam' => $whichteam,
						'who' => $who
					)
				);
				echo $txt['bnt_team_plinvted'], '<br>';
				playerlog($who,LOG_TEAM_INVITE,"$team[team_name]");
			}
		}
		else
			echo $txt['bnt_team_notyours'], '<br>';
	}
	echo '<br><br><a href="', $scripturl, '?action=blacknova;sa=teams">', $txt['bnt_clickme'], '</a> ', $txt['bnt_team_menu'], '<br><br>';
}
// Player chooses to refuse invitation to an alliance.
elseif ($teamwhat == 8)
{
	echo $txt['bnt_team_refuse'], ' <b>', $invite_info['team_name'], '</b>.<br><br>';
	
	$update = $smcFunc['db_query']('', '
		UPDATE {raw:db_ships}
		SET team_invite = 0
		WHERE ship_id = {int:ship_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'ship_id' => $playerinfo['ship_id']
		)
	);
	
	playerlog($team['creator'], LOG_TEAM_REJECT, "$playerinfo[character_name]|$invite_info[team_name]");
	LinkBack();
}
// Player is editing an alliance
elseif ($teamwhat == 9)
{
	// Read query string variables.
	if (isset($_POST['update']))
		$update = $_POST['update'];
	else
		$update = '';
	
	if (isset($_POST['teamname']))
		$teamname = $_POST['teamname'];
	else
		$teamname = '';
		
	if (isset($_POST['teamdesc']))
		$teamdesc = $_POST['teamdesc'];
	else
		$teamdesc = '';

	if ($playerinfo['team'] == $whichteam) {
		if (empty($update))
		{
			echo '
		<form action="', $scripturl, '?action=blacknova;sa=teams" method="post">
			', $txt['bnt_team_edname'], ': <br>
			<input type="hidden" name="teamwhat" value="', $teamwhat, '">
			<input type="hidden" name="whichteam" value="', $whichteam, '">
			<input type="hidden" name="update" value="true">
			<input type="text" name="teamname" size="40" maxlength="40" value="', $team['team_name'], '"><br>
			', $txt['bnt_team_eddesc'], ': <br>
			<input type="text" name="teamdesc" size="40" maxlength="254" value="', $team['description'], '"><br>
			<input type="submit" value="', $txt['bnt_submit'], '><input type="reset" value="', $txt['bnt_reset'], '">
		</form>
		<br><br>';
		}
		else
		{
			$teamname = htmlspecialchars($teamname);
			$teamdesc = htmlspecialchars($teamdesc);
			
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_teams}
				SET team_name = {string:team_name},
					description = {string:description}
				WHERE id = {int:whichteam}',
				array(
					'db_teams' => $dbtables['teams'],
					'team_name' => $team_name,
					'description' => $description,
					'whichteam' => $whichteam
				)
			);
			
			echo $txt['bnt_team_alliance'], ' <b>', $teamname, '</b> ', $txt['bnt_team_hasbeenr'], '<br><br>';
			
			// Add a log entry to all members of the renamed alliance.
			playerlog($playerinfo['ship_id'], LOG_TEAM_RENAME, "$teamname");
			
			$result = $smcFunc['db_query']('', '
				SELECT ship_id
				FROM {raw:db_ships}
				WHERE team = {int:whichteam}
				AND ship_id <> {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'whichteam' => $whichteam,
					'ship_id' => $playerinfo['ship_id']
				)
			);

			while($row = $smcFunc['db_fetch_assoc']($result))
			{
				playerlog($row['ship_id'], LOG_TEAM_M_RENAME, "$teamname");
			}
			$smcFunc['db_free_result']($result);
		}
		LinkBack();
	}
	else
	{
		echo $txt['bnt_team_error'];
		LinkBack();
	}
}
else
{
	if (!$playerinfo['team'])
	{
		echo $txt['bnt_team_notmember'];
		DisplayInviteInfo($playerinfo,$invite_info);
	}
	else
	{
		if ($playerinfo['team'] < 0)
		{
			$playerinfo['team'] = -$playerinfo['team'];
			
			$result = $smcFunc['db_query']('', '
				SELECT *
				FROM {raw:db_teams}
				WHERE id = {int:team}',
				array(
					'db_teams' => $dbtables['teams'],
					'team' => $playerinfo['team']
				)
			);
			
			$whichteam = $smcFunc['db_fetch_assoc']($result);
			$smcFunc['db_free_result']($result);
			echo $txt['bnt_team_urejected'], ' <b>', $whichteam['team_name'], '</b><br><br>';

			LinkBack();
			break;
		}
		
		$result = $smcFunc['db_query']('', '
			SELECT *
			FROM {raw:db_teams}
			WHERE id = {int:team}',
			array(
				'db_teams' => $dbtables['teams'],
				'team' => $playerinfo['team']
			)
		);
		$whichteam = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		
		if ($playerinfo['team_invite'])
		{
			$result = $smcFunc['db_query']('', '
				SELECT *
				FROM {raw:db_teams}
				WHERE id = {int:team_invite}',
				array(
					'db_teams' => $dbtables['teams'],
					'team_invite' => $playerinfo['team_invite']
				)
			);
			$whichinvitingteam = $smcFunc['db_fetch_assoc']($result);
			$smcFunc['db_free_result']($result);
		}
		
		$isowner = $playerinfo['ship_id'] == $whichteam['creator'];
		showinfo($playerinfo['team'],$isowner,$playerinfo,$invite_info,$team);
	}
	
	$result = $smcFunc['db_query']('', '
		SELECT COUNT(*) AS total
		FROM {raw:db_teams}',
		array(
			'db_teams' => $dbtables['teams']
		)
	);
	$num_res = $smcFunc['db_fetch_assoc']($result);
	if ($num_res['total'] > 0)
		DisplayAllAlliances();
	else
		echo $txt['bnt_team_noalliances'], '<br><br>';
}

echo '<br><br>';
TextMainMenu();

//
// Begin Team functions
//
function LinkBack()
{
	global $txt, $scripturl;
	
	echo '<br><br><a href="', $scripturl, '?action=blacknova;sa=teams">', $txt['bnt_clickme'], '</a> ', $txt['bnt_team_menu'], '.<br><br>';
}

function DisplayAllAlliances()
{
	global $smcFunc, $txt, $scripturl;
	global $color, $color_header;
	global $order, $type;
	global $dbtables;

	$type = (isset($_GET['type'])) ? stripnum($_GET['type']) : '';
	$order = (isset($_GET['order'])) ? stripnum($_GET['order']) : '';
	
	echo '
		<br><br>', $txt['bnt_team_galax'], '<br>
		<table width="100%" border=0 cellspacing=0 cellpadding=2>
			<tr bgcolor="', $color_header, '">';

	if ($type == "d") {
		$type = "a";
		$by = "ASC";
	}
	else
	{
		$type = "d";
		$by = "DESC";
	}
	
	echo '
				<td><b><a href="', $scripturl, '?action=blacknova;sa=teams;order=team_name;type=', $type, '">', $txt['bnt_name'], '</a></b></td>
				<td><b><a href="', $scripturl, '?action=blacknova;sa=teams;order=team_name;type=', $type, '">', $txt['bnt_team_members'], '</a></b></td>
				<td><b><a href="', $scripturl, '?action=blacknova;sa=teams;order=character_name;type=', $type, '">', $txt['bnt_team_coord'], '</a></b></td>
				<td><b><a href="', $scripturl, '?action=blacknova;sa=teams;order=total_score;type=', $type, '">', $txt['bnt_score'], '</a></b></td>
			</tr>';
   
	$query =	'SELECT ' . $dbtables['ships'] . '.character_name,
					COUNT(*) as number_of_members,
					ROUND(SQRT(SUM(POW(' . $dbtables['ships'] . '.score,2)))) as total_score,
					' . $dbtables['teams'] . '.id,
					' . $dbtables['teams'] . '.team_name,
					' . $dbtables['teams'] . '.creator
				FROM ' . $dbtables['ships'] . '
				LEFT JOIN ' . $dbtables['teams'] . ' ON ' . $dbtables['ships'] . '.team = ' . $dbtables['teams'] . '.id
				WHERE ' . $dbtables['ships'] . '.team = ' . $dbtables['teams'] . '.id
				GROUP BY ' . $dbtables['teams'] . '.team_name';
	
	//  Setting if the order is Ascending or descending, if any.  Default is ordered by teams.team_name
	if ($order)
		$query = $sql_query . ' ORDER BY ' . $order . ' ' . $by;
	
	$result = $smcFunc['db_query']('', 
		$query,
		''
	);
	
	while($row = $smcFunc['db_fetch_assoc']($result))
	{
		echo '
			<tr bgcolor="', $color, '">
				<td><a href="', $scripturl, '?action=blacknova;sa=teams;teamwhat=1;whichteam=', $row['id'], '">', $row['team_name'], '</a></td>
				<td>', $row['number_of_members'], '</td>';
	
		// This fixes it so that it actually displays the coordinator, and not the first member of the team.
		$coordinator_result = $smcFunc['db_query']('', '
			SELECT character_name
			FROM {raw:db_ships}
			WHERE ship_id = {int:creator}
			LIMIT 1',
			array(
				'db_ships' => $dbtables['ships'],
				'creator' =>  $row['creator']
			)
		);
		
		$coordinator = $smcFunc['db_fetch_assoc']($coordinator_result);
		$smcFunc['db_free_result']($coordinator_result);
	
	    echo '
					<td><a href="', $scripturl, '?action=blacknova;sa=mailto;to=', $coordinator['character_name'], '">', $coordinator['character_name'], '</a></td>
				    <td>', $row['total_score'], '</td>
				</tr>';		
   }
   
   $smcFunc['db_free_result']($result);
   
   echo '
		</table><br>';
}

function DisplayInviteInfo($playerinfo,$invite_info)
{
	global $txt, $scripturl;
	
	if (!$playerinfo['team_invite'])
	{
		echo '
			<br><br><font color="blue" size="2"><b>', $txt['bnt_team_noinvite'], '</b></font><br>
			', $txt['bnt_team_ifyouwant'], '<br>
			<a href="', $scripturl, '?action=blacknova;sa=teams;teamwhat=6">', $txt['bnt_clickme'], '</a> ', $txt['bnt_team_tocreate'], '<br><br>';
	}
	else
	{
	   echo '
			<br><br><font color="blue" size="2"><b>', $txt['bnt_team_injoin'], ' 
			<a href="', $scripturl, '?action=blacknova;sa=teams;teamwhat=1;whichteam=', $playerinfo['team_invite'], '">', $invite_info['team_name'], '</a></b></font>!<br><br>
			<a href="', $scripturl, '?action=blacknova;sa=teams;teamwhat=3;whichteam=', $playerinfo['team_invite'], '">', $txt['bnt_clickme'], '</a> ', $txt['bnt_team_tojoin'], ' <b>', $invite_info['team_name'], '</b> ', $txt['bnt_team_or'], ' <a href="', $scripturl, '?action=blacknova;sa=teamwhat=8;whichteam=', $playerinfo['team_invite'], '">', $txt['bnt_clickme'], '</a> ', $txt['bnt_team_reject'], '<br><br>';
	}
}


function showinfo($whichteam,$isowner,$playerinfo,$invite_info,$team)
{
	global $smcFunc, $txt, $scripturl;
	global $dbtables, $color_header, $color_line1, $color_line2;

	// Display table header.
	echo '
			<div align=center>
				<h3><font color="white"><b>', $team['team_name'], '</b>
				<br><font size="2">"<i>', $team['description'], '</i>"</font></h3>';
				
	if ($playerinfo['team'] == $team['id'])
	{
		echo '
				<font color="white">';	
				
		if ($playerinfo['ship_id'] == $team['creator'])
			echo $txt['bnt_team_coord'], ' ';
		else
			echo $txt['bnt_team_member'], ' ';
			
		echo $txt['bnt_options'], '<br><font size="2">';
		
		if ($playerinfo['ship_id'] == $team['creator'])
			echo '[<a href="', $scripturl, '?action=blacknova;sa=teams;teamwhat=9;whichteam=', $playerinfo['team'], '">', $txt['bnt_team_ed'], '</a>] - ';

		echo '[<a href="', $scripturl, '?action=blacknova;sa=teams;teamwhat=7;whichteam=', $playerinfo['team'], '">', $txt['bnt_team_inv'], '</a>] - [<a href="', $scripturl, '?action=blacknova;sa=teams;teamwhat=2;whichteam=', $playerinfo['team'], '">', $txt['bnt_team_leave'], '</a>]</font></font>';
	}
	DisplayInviteInfo($playerinfo,$invite_info);
	echo '
			</div>';

	//Display main table.
    echo '
			<table border="2" cellspacing="2" cellpadding="2" bgcolor="#400040" width="75%" align="center">
				<tr>
					<td><font color="white">', $txt['bnt_team_members'], '</font></td>
				</tr>
				<tr bgcolor="', $color_line2, '">';
	
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_ships}
		WHERE team = {int:whichteam}',
		array(
			'db_ships' => $dbtables['ships'],
			'whichteam' => $whichteam
		)
	);

    while ($member = $smcFunc['db_fetch_assoc']($result))
	{
		echo '
					<td> - ', $member['character_name'], ' (', $txt['bnt_score'], ' ', $member['score'], ')';
		
		if ($isowner && ($member['ship_id'] != $playerinfo['ship_id']))
			echo ' - <font size="2">[<a href="', $scripturl, '?action=blacknova;sa=teams;teamwhat=5;who=', $member['ship_id'], '">', $txt['bnt_team_eject'], '</a>]</font></td>';
		elseif ($member['ship_id'] == $team['creator'])
			echo ' - ', $txt['bnt_team_coord'], '</td>';
			
		echo '
				</tr>
				<tr bgcolor="', $color_line2, '">';
    }
	$smcFunc['db_free_result']($result);
	
	// Displays for members name
	echo '
					<td bgcolor="', $color_line2, '"><font color="white">', $txt['bnt_team_pending'], ' <b>', $team['team_name'], '</b></font></td>
				</tr>
				<tr>';
	
	$result = $smcFunc['db_query']('', '
		SELECT ship_id,character_name
		FROM {raw:db_ships}
		WHERE team_invite = {int:whichteam}',
		array(
			'db_ships' => $dbtables['ships'],
			'whichteam' => $whichteam
		)
	);
    if ( $smcFunc['db_num_rows']($result) > 0)
	{
		echo '
				</tr>
				<tr bgcolor="', $color_line2, '">';
		while ($who = $smcFunc['db_fetch_assoc']($result))
		{
			echo '
					<td> - ', $who['character_name'], '</td>
				</tr>
				<tr bgcolor="', $color_line2, '">';
		}
    }
	else
	{
		echo '
					<td>', $txt['bnt_team_noinvites'], ' <b>', $team['team_name'], '</b>.</td>
				</tr>
				<tr>';
    }
	
    echo '
				</tr>
			</table>';
}
?>